import {PlusOutlined, ExportOutlined} from '@ant-design/icons';
import {
    ActionType,
    ProColumns,
    ProForm,
    ProFormContext,
    ProFormInstance,
    ProFormText
} from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer,
    ProTable,
    ProDescriptions,
} from '@ant-design/pro-components';
import {Button, Modal, Menu} from 'antd';
import { DatePicker, Space, Typography } from 'antd';
const { RangePicker } = DatePicker;
import React, {useRef, useState, useEffect} from 'react';
import type {BillingListItem} from './data';
import {ProCard} from '@ant-design/pro-components';
import {Statistic} from 'antd';
import RcResizeObserver from 'rc-resize-observer';
const {confirm} = Modal;
const {Divider} = ProCard;
import {useForm} from 'antd/lib/form/Form';
import {
    ResourceTypeEnum
} from '../../data.enum'
import moment from 'moment';

import {billingList, billingStatisticsOverview} from './service';
import {organizationSelectList} from "@/pages/organization/org-list/service";
import AddNetworkModalForm from "@/pages/power/network/add";
import ExportBillingNoticeModalForm from "@/pages/order/billing/list/export";
import {BillingExportData, BillingOverview} from "./data";

import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

const BillingList: React.FC = () => {
    /** 新建窗口的弹窗 */
    const actionRef = useRef<ActionType>();
    const actionRefTableExtraRender = useRef<ActionType>();
    const proTableFormRef = useRef<ProFormInstance>();
    const [dates, setDates] = useState([]);
    const [billingOverviewData, setBillingOverviewData] = useState<BillingOverview>();
    const [billingOverviewLoading, setBillingOverviewbillingOverviewLoading] = useState<false>();
    const [isChange, setIsChange] = useState(false);
    const [responsive, setResponsive] = useState(false);
    const [exportBillingNoticeModalVisible, handleExportBillingNoticeModalVisible] = useState<boolean>(false);

    // 导出通知单按钮事件
    const handleExportBillingNoticeButton = () => {
        const organizationId = proTableFormRef?.current?.getFieldValue("organizationId");
        console.log('organizationId:', organizationId);
        if (organizationId === null || organizationId == undefined || organizationId === '') {
            confirm({
                title: '无法导出账单通知',
                content: '请选择租户，并点击查询按钮后，再次导出',
            });
            return true
        }

        handleExportBillingNoticeModalVisible(true);
        return true
    }

    useEffect(() => {
        fetchBillingOverview().then(r => {

        });
    }, []);

    const fetchBillingOverview = async () => {
        const organizationId = proTableFormRef?.current?.getFieldValue("organizationId");
        const resourceId = proTableFormRef?.current?.getFieldValue("resourceId");
        const resourceType = proTableFormRef?.current?.getFieldValue("resourceType");
        const billingTimeRange = proTableFormRef?.current?.getFieldValue("billingTime");
        const result = await billingStatisticsOverview({
            "organizationId": organizationId,
            "resourceId": resourceId,
            "resourceType": resourceType,
            "billingTimeRange": billingTimeRange,
            "startTime": moment(billingTimeRange?.[0]).format('YYYY-MM-DD HH:mm'),
            "endTime": moment(billingTimeRange?.[1]).format('YYYY-MM-DD HH:mm'),
        });
        if (result.success) {
            const billingOverviewData: BillingOverview = {
                serviceCost: result.data.serviceCost,
                billingCount: result.data.billingCount,
                resourceTypeCount: result.data.resourceTypeCount,
                organizationName: result.data.organizationName,
                organizationAddress: result.data.organizationAddress,
            };
            setBillingOverviewData(billingOverviewData)
        }
    };

    const onOpenChange = (open: any) => {
        if (open && (!dates?.[0] || !dates?.[1])) {
            setDates([]);
        }
    };

    const disabled180DaysDate = (current, { from }) => {
        if (from) {
            return Math.abs(current.diff(from, 'days')) >= 180;
        }
        return false;
    };

    /** 国际化配置 */
    const columns: ProColumns<BillingListItem>[] = [
        {
            title: '账期',
            dataIndex: 'billingMonth',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '账期范围',
            dataIndex: 'billingTime',
            hideInTable: true,
            initialValue: [moment().subtract(1, 'months'), moment()],
            renderFormItem: () => {
                return (
                    // <DatePicker.RangePicker
                    //     onOpenChange={onOpenChange}
                    //     onCalendarChange={(val) => setDates(val)}
                    //     placeholder={['开始日期', '结束日期']}
                    //     allowClear={false}
                    //     disabledDate={disabled7DaysDate}
                    //     style={{width: "240px"}}
                    // />

                    <RangePicker
                        disabledDate={disabled180DaysDate}
                        placeholder={['开始日期', '结束日期']}
                        style={{width: "240px"}}
                        allowClear={false}
                        onCalendarChange={(val) => setDates(val)}
                        onOpenChange={onOpenChange}
                    />
                );
            },
        },
        {
            title: '关联订单',
            dataIndex: 'orderId',
            search: false,
            // hidden: true,
            width: 160,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '租户',
            dataIndex: "organizationId",
            valueType: 'select',
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await organizationSelectList({includeSystem: false});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.organizationId,
                    })) || []
                );
            },
        },
        {
            title: '租户',
            dataIndex: 'organizationName',
            search: false,
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '产品类型',
            dataIndex: 'resourceTypeName',
            search: false,
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '产品类型',
            dataIndex: 'resourceType',
            search: true,
            valueType: 'select',
            valueEnum: ResourceTypeEnum,
            hidden: true,
        },
        {
            title: '产品明细',
            dataIndex: 'resourceName',
            search: false,
            hidden: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '产品单价',
            dataIndex: 'unitPrice',
            search: false,
            width: 150,
            ellipsis: true, // 关闭自动换行
            renderText: (val: string) => (
                <span style={{color: '#057A68'}}>{val}</span>
            ),
        },

        {
            title: '费用时间',
            dataIndex: 'billingTimeRange',
            search: false,
            width: 330,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '计费',
            dataIndex: 'cost',
            search: false,
            ellipsis: true, // 关闭自动换行
            renderText: (val: string) => (
                <span style={{color: '#057A68'}}>￥{val}</span>
            ),
        },
    ];
    return (
        <PageContainer>
            <ProTable<BillingListItem, API.ListPagination>
                headerTitle="账单列表"
                actionRef={actionRef}
                formRef={proTableFormRef}
                rowKey="billingId"
                scroll={{x: true}}
                search={{
                    labelWidth: 120,
                }}
                request={billingList}
                columns={columns}
                rowSelection={false}
                options={{
                    density: true,
                    fullScreen: true,
                    reload: true,
                    setting: false
                }}
                onSubmit={fetchBillingOverview}

                tableExtraRender={(_, data) => (
                    <RcResizeObserver
                        key="resize-observer"
                        onResize={(offset) => {
                            setResponsive(offset.width < 596);
                        }}
                    >
                        <ProCard.Group
                            title="账单统计"
                            direction={responsive ? 'column' : 'row'}
                            extra={
                                <Button
                                    type="primary"
                                    key="primary"
                                    onClick={() => {
                                        handleExportBillingNoticeButton();
                                    }}
                                    disabled={false}
                                >
                                    <ExportOutlined/> 生成通知单
                                </Button>}
                        >
                            <ProCard>
                                <Statistic title="账单总数" value={billingOverviewData?.billingCount} precision={0}/>
                            </ProCard>
                            <Divider type={responsive ? 'horizontal' : 'vertical'}/>
                            <ProCard>
                                <Statistic title="资源类别" value={billingOverviewData?.resourceTypeCount} precision={0}/>
                            </ProCard>
                            <Divider type={responsive ? 'horizontal' : 'vertical'}/>
                            <ProCard>
                                <Statistic title="服务费用" value={billingOverviewData?.serviceCost} precision={2} prefix="¥"/>
                            </ProCard>
                        </ProCard.Group>
                    </RcResizeObserver>
                )}
            />
            <ExportBillingNoticeModalForm
                modalVisible={exportBillingNoticeModalVisible}
                onClose={() => {
                    handleExportBillingNoticeModalVisible(false);
                }}
                onSuccess={() => {
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }}
                initData={{
                    organizationName:billingOverviewData?.organizationName,
                    organizationAddress:billingOverviewData?.organizationAddress,
                    serviceCost:billingOverviewData?.serviceCost,
                    billingStartTime: proTableFormRef?.current?.getFieldValue("billingTime")[0],
                    billingEndTime: proTableFormRef?.current?.getFieldValue("billingTime")[1],
                } as BillingExportData}
            />
        </PageContainer>
    );
};

export default BillingList;
